package com.qingfeng.client.api;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qingfeng.client.DO.PreTradeDo;
import com.qingfeng.client.bean.Buyer;
import com.qingfeng.client.service.RedisService;
import com.qingfeng.exception.LsException;
import com.qingfeng.util.ApiMsg;
import com.qingfeng.util.CodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 基础接口
 * @author zhangyuefei
 * @version 1.0
 * @date 2020/1/2 4:19 下午
 */
public class BaseV1Api {

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    private RedisService redisService;

    public Buyer getUser(){
        Buyer buyer =  (Buyer) request.getSession().getAttribute("buyerBean");
        if (buyer==null){
            throw new LsException(CodeEnum.ERROR,"请先授权登录");
        }
        return buyer;
    }

    public void setUser(Buyer buyer){
       request.getSession().setAttribute("buyerBean",buyer);
    }

    public PreTradeDo getPreTrade(){
        String str =  (String) request.getSession().getAttribute("preTradeDo");
        if (StringUtils.isEmpty(str)){
            throw new LsException(CodeEnum.ERROR,"无正在创建的订单");
        }
        PreTradeDo preTradeDo = JSON.parseObject(str,PreTradeDo.class);
        return preTradeDo;
    }

    public void setPreTrade(PreTradeDo tredeDo){
        String str = JSON.toJSONString(tredeDo);
        request.getSession().setAttribute("preTradeDo",str);
    }

    public Buyer getUserByToken(){
        return getUser();
//        String token = request.getHeader("token");
//       return (Buyer) redisService.getToken(token);
    }

    public ApiMsg returnFlag(boolean flag){
        if (flag){
            return success();
        }else {
            return error();
        }
    }

    public ApiMsg returnFlag(int flag){
        if (flag > 0){
            return success();
        }else {
            return error();
        }
    }

    public ApiMsg error(){
        return new ApiMsg(0,"失败",null);
    }

    public ApiMsg error(String msg){
        return new ApiMsg(0,msg,null);
    }

    public ApiMsg success(){
        return new ApiMsg(1,"成功",null);
    }

    public ApiMsg success(String msg){
        return new ApiMsg(1,msg,null);
    }
    public ApiMsg success(String msg,Object data){
        return new ApiMsg(1,msg,data);
    }

    public ApiMsg success(Object data){
        return new ApiMsg(1,"成功",data);
    }

    public ApiMsg successPage(IPage page){
        return new ApiMsg(1,"成功",page);

    }
}
